package com.gszy.auth.controller;


import com.gszy.auth.entity.Users;
import com.gszy.auth.mvc.BeanFactory;
import com.gszy.auth.mvc.Controller;
import com.gszy.auth.mvc.ModelAndView;
import com.gszy.auth.mvc.RequestMapping;
import com.gszy.auth.security.UserDetails;
import com.gszy.auth.service.UserService;
import com.gszy.auth.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

@Controller("/auth")
public class LoginController {

    private UserService userService = BeanFactory.getInstance(UserService.class);

    @RequestMapping("/login.do")
    public ModelAndView login(Users users, HttpServletRequest request) throws NoSuchAlgorithmException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setPath("/pages/login.jsp");

        UserDetails userDetails = userService.loadUserByUsername(users.getUsername());
        if (userDetails == null){
            modelAndView.add("msg","用户名或者密码错误！");
            return modelAndView;
        }

        String md5Encode = StringUtils.getMd5Encode(users.getPassword());
        if (userDetails.getPassword().equals(md5Encode)){
            request.getSession().setAttribute("auth",userDetails);
            modelAndView.setPath("/pages/main.jsp");
            return modelAndView;

        }else {
            modelAndView.add("msg","用户名或者密码错误");
            return modelAndView;
        }



    }
}
